const express = require("express");
const router = express.Router();
const passport = require("passport");
const Report = require("../../../models/Report");
const errorHandler = require("../../../middlewares/errorHandler");
const fileRoutes = require("../uploadfile");
const fs = require("fs");
const path = require("path");

const auth = passport.authenticate("jwt", { session: false });

// @路由  GET api/report/test
router.get("/test", (req, res) => res.json({ msg: "report works" }));

// @路由  POST api/report/add
router.post("/add", auth, async (req, res) => {
  try {
    const report = await Report.create(req.body);
    console.log("添加报告成功:", report);
    res.status(200).json({ success: true, data: report });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @路由  GET api/report
router.get("/", auth, async (req, res) => {
  try {
    const reports = await Report.find();
    console.log("获取报告成功:", reports);
    res
      .status(200)
      .json({ success: true, count: reports.length, data: reports });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @路由  GET api/report/:id
router.get("/:id", auth, async (req, res) => {
  try {
    const report = await Report.findById(req.params.id);
    if (!report) {
      console.error("未找到报告");
      return res.status(404).json({ success: false, error: "未找到报告" });
    }
    console.log("获取单个报告成功:", report);
    res.status(200).json({ success: true, data: report });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @路由  POST api/report/edit
router.post("/edit", auth, async (req, res) => {
  try {
    const { _id, ...updateData } = req.body;
    const report = await Report.findByIdAndUpdate(_id, updateData, {
      new: true,
    });
    if (!report) {
      console.error("未找到报告");
      return res.status(404).json({ success: false, error: "未找到报告" });
    }
    console.log("编辑报告成功:", report);
    res.status(200).json({ success: true, data: report });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @路由  DELETE api/report/delete
router.delete("/delete", auth, async (req, res) => {
  try {
    const { _id } = req.body;
    const report = await Report.findById(_id);
    if (!report) {
      console.error("未找到报告");
      return res.status(404).json({ success: false, error: "未找到报告" });
    }
    const photoUrls = report.photos;
    await Report.findByIdAndRemove(_id);
    console.log("删除报告成功:", report);
    photoUrls.forEach((photoUrl) => {
      const filename = path.basename(photoUrl);
      const filePath = path.join(__dirname, "../../public/uploads/", filename);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
        console.log("删除文件成功:", filename);
      } else {
        console.error("未找到文件:", filename);
      }
    });
    res.status(200).json({ success: true, data: report });
  } catch (err) {
    errorHandler(res, err);
  }
});

// 引入文件上传路由
router.use(fileRoutes);

module.exports = router;
